package ee.serge.client.content.cp;

import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.PopupPanel;
import com.google.gwt.user.client.ui.VerticalPanel;

import ee.serge.client.AlertBox;
import ee.serge.client.Move;
import ee.serge.service.Service;
import ee.serge.shared.Admin;
import ee.serge.shared.ContentPopup;
import ee.serge.util.BTextBox;
import ee.serge.util.FormPanel;
import ee.serge.util.SimpleCallback;
import ee.serge.util.bootstrap.BButton;
import ee.serge.util.bootstrap.BButtonBar;

public class AccountAddPopup extends ContentPopup {

	public static void showAdd() {
		PopupPanel instance = new AccountAddPopup();
        instance.center();
        instance.show();
	}
	
	private BTextBox username;
	private BTextBox password;
	private BTextBox name;
	private BTextBox email;

	public AccountAddPopup() {
		VerticalPanel panel = new VerticalPanel();
		FormPanel form = new FormPanel();
		form.add("Username", username = new BTextBox());
		form.add("Password", password = new BTextBox());
		form.add("Name", name = new BTextBox());
		form.add("Email", email = new BTextBox());
		
		BButtonBar buttonBar = new BButtonBar();
		buttonBar.add(new BButton("Add", BButton.PRIMARY, new SaveHandler()));
		buttonBar.add(new BButton("Cancel", new CloseHandler()));
		
		panel.add(form);
		panel.add(buttonBar);
		
		add(panel);
	}
	
	private Admin getAdmin() {
		return new Admin(
				username.getText(), 
				password.getText(), 
				name.getText(), 
				email.getText());
	}
	
	private class SaveHandler implements ClickHandler {

		@Override
		public void onClick(ClickEvent event) {
			Service.getControlPanelService().registerAccount(getAdmin(), new SimpleCallback<Void>() {

				@Override
				public void success(Void result) {
					Move.get().refresh();
					AlertBox.showSuccess("Account added");
					hide();
				}
			});
		}
		
	}
	
	private class CloseHandler implements ClickHandler {

      @Override
      public void onClick(ClickEvent event) {
         AccountAddPopup.this.hide();
      }
      
   }
	
}
